package com.bndg.dnttapwhite

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity(), OnGameOverListener {
    private var paused: Boolean = false
    var gameView: GameSurfaceView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        gameView = GameSurfaceView(this)
        setContentView(gameView)
        // 设置游戏结束监听器
        gameView?.setOnGameOverListener(this)
    }

    override fun onResume() {
        super.onResume()
        if (paused) {
            paused = false
            gameView?.resumeGame()
        }
    }

    override fun onPause() {
        super.onPause()
        paused = true
        gameView?.pauseGame()
    }

    override fun onGameOver(score: Int) {
        // 从sp中获取分数
        val sharedPreferences = getSharedPreferences("game_data", MODE_PRIVATE)
        val highScore = sharedPreferences.getInt("high_score", 0)
        var tips = "分数: $score"
        if (score > highScore) {
            // 更新最高分
            tips = "分数: $score 新纪录！"
            // 如果当前得分大于最高分，则更新最高分
            sharedPreferences.edit().putInt("high_score", score).apply()
        }
        lifecycleScope.launch {
            // 弹出对话框
            AlertDialog.Builder(this@MainActivity)
                .setTitle("Game Over")
                .setMessage(tips)
                .setPositiveButton("Restart") { dialog, _ ->
                    gameView?.restartGame()
                    dialog.dismiss()
                }
                .setCancelable(false)
                .show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        gameView?.release()
    }
}